package com.yzf.demo.demo.DesignPattren.SingletonPattern.containersingleton;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by 于占峰 on 2020/2/29/029.
 * 加入双重校验锁 防止线程安全问题
 */
public class IocSingletonThread {
    private static Map<String, Object> iocMap = new ConcurrentHashMap<>();

    public IocSingletonThread() {
    }

    public static Object getBean(String className) {
        Object bean = null;
        //双层校验锁
        if (!iocMap.containsKey(className)) {
            synchronized (IocSingletonThread.class) {
                if (!iocMap.containsKey(className)) {
                    try {
                        bean = Class.forName(className).newInstance();
                        iocMap.put(className, bean);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return bean;
                } else {
                    return iocMap.get(className);
                }
            }
        }
        return iocMap.get(className);
    }
}
